package com.skyable.common.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * 接口实例工厂，这里主要是用于提供接口的实例对象
 * @author gaoyuan
 * @param <T>
 */
@Data
@Slf4j
public class ServiceFactory<T> implements FactoryBean<T> {

    private Class<T> interfaceType;
    private String requestUrl;

    public ServiceFactory(Class<T> interfaceType, String requestUrl) {
        log.info("get config info interfaceType:" + interfaceType + ";requestUrl:" + requestUrl);
        this.interfaceType = interfaceType;
        this.requestUrl = requestUrl;
    }

    @Override
    public T getObject() throws Exception {
        //这里主要是创建接口对应的实例，便于注入到spring容器中
        InvocationHandler handler = new ServiceProxy(requestUrl);
        return (T) Proxy.newProxyInstance(interfaceType.getClassLoader(),
                new Class[] {interfaceType},handler);
    }

    @Override
    public Class<T> getObjectType() {
        return interfaceType;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
